package com.bss.service;

import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.andy.basics.Dao;
import com.bss.dao.ActivityDao;
import com.bss.dao.ActivityTypeDao;
import com.bss.dao.PaymentDao;
import com.bss.dao.RevenueDao;
import com.bss.dao.RevenueHeadDao;
import com.bss.model.Activity;
import com.bss.model.ActivityType;
import com.bss.model.DailyRevenue;
import com.bss.model.Payment;
import com.bss.model.Revenue;
import com.bss.model.RevenueHead;

@Service
@Scope("session")
public class DailyRevenueService extends com.andy.basics.Service<DailyRevenue> {

	@Autowired
	private RevenueDao revenueDao;

	@Autowired
	private PaymentDao paymentDao;

	@Autowired
	private ActivityDao activityDao;

	@Autowired
	private ActivityTypeDao activityTypeDao;

	@Autowired
	private RevenueHeadDao revenueHeadDao;

	private List<RevenueHead> revenueHeads;

	private ActivityType activityType;

	@Override
	public Dao<DailyRevenue> getDao() {
		throw new UnsupportedOperationException();
	}

	@Override
	@Transactional
	public void save(final DailyRevenue dailyRevenue) {
		for (Revenue revenue : dailyRevenue.getRevenues()) {
			this.revenueDao.persist(revenue);
		}
		Activity activity = new Activity();
		activity.setActivityType(getActivityType());
		activity.setActivityDate(dailyRevenue.getDate());
		activity.setDescription(null);
		this.activityDao.persist(activity);
	}

	public void setRevenueHeads(final List<RevenueHead> revenueHeads) {
		this.revenueHeads = revenueHeads;
	}

	public List<RevenueHead> getRevenueHeads() {
		if (this.revenueHeads == null) {
			this.revenueHeads = this.revenueHeadDao.findAll();
		}
		return this.revenueHeads;
	}

	public List<Payment> getPayments(final Date tillDate) {
		Activity activity = this.activityDao
				.findLastActivity(getActivityType());
		if (activity == null) {
			return null;
		}
		List<Payment> payments = this.paymentDao.findPayments(
				activity.getActivityDate(), tillDate);
		return payments;
	}

	public Activity getLastActivity() {
		return this.activityDao.findLastActivity(getActivityType());
	}

	public ActivityType getActivityType() {
		if (this.activityType == null) {
			List<ActivityType> activityTypes = this.activityTypeDao
					.find("name='Daily Revenue Report'");
			this.activityType = activityTypes.get(0);
		}
		return this.activityType;
	}

}
